package zj.com.activities;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import zj.com.adapter.DzgDetailAdapter;
import zj.com.app.ZjApplication;
import zj.com.db.DBUtil;
import zj.com.model.Dic;
import zj.com.model.Dzg;
import zj.com.model.DzgDetail;
import zj.com.model.DzgDetailDB;
import zj.com.model.DzgInspectItemDB;
import zj.com.model.DzgInspectTask;
import zj.com.model.UploadFile;
import zj.com.model.User;
import zj.com.net.NetManager;
import zj.com.net.OnResponseListener;
import zj.com.util.Constants;
import zj.com.util.DateUtil;
import zj.com.util.DialogUtil;
import zj.com.util.LogUtils;
import zj.com.zj.R;

/**
 * Created by xi on 16/6/10.
 *
 * 待整改详情
 */
public class TestDzgDetailActivity extends  BaseActivity implements View.OnClickListener {


    public TextView title_name,right_tv,upload_tv;
    public ImageView left_iv;
    public ListView listView;
    public List<DzgInspectTask> list;
    public DzgDetailAdapter adapter;

    public TextView rw_tv,yh_tv,jczy_tv,jcx_tv,gs_tv,xm_tv,jcType_tv,end_date_tv;

    public DbManager dbManager;

    public RelativeLayout check_rl;
    public TextView check_value_tv;

    public final int JCR= 0x2210;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dzg_detail);
        dbManager = DBUtil.getInstance(this).getDBManager();

        initView();
        initData();
    }

    public void initView(){

        check_rl = (RelativeLayout) findViewById(R.id.check_rl);
        check_rl.setOnClickListener(this);
        check_value_tv = (TextView) findViewById(R.id.check_value_tv);
        title_name = (TextView) findViewById(R.id.title_name);
        title_name.setText("问题整改");
        right_tv = (TextView) findViewById(R.id.right_tv);
        right_tv.setOnClickListener(this);
        right_tv.setText("保存");
        left_iv = (ImageView) findViewById(R.id.left_iv);
        left_iv.setOnClickListener(this);
        left_iv.setVisibility(View.VISIBLE);

        listView = (ListView) findViewById(R.id.listView);

        rw_tv = (TextView) findViewById(R.id.rw_value_tv);
        yh_tv = (TextView) findViewById(R.id.yh_value_tv);
        jczy_tv = (TextView) findViewById(R.id.jczy_vale_tv);
        jcx_tv = (TextView) findViewById(R.id.jcx_value_tv);
        gs_tv = (TextView) findViewById(R.id.gs_value_tv);
        xm_tv = (TextView) findViewById(R.id.xm_value_tv);
        jcType_tv = (TextView) findViewById(R.id.jc_type_value_tv);
        end_date_tv = (TextView) findViewById(R.id.end_date_value_tv);

        upload_tv = (TextView) findViewById(R.id.upload_tv);
        upload_tv.setOnClickListener(this);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(TestDzgDetailActivity.this, DzgDetailEditActivity.class);
                intent.putExtra("task",tasks.get(position));
                startActivity(intent);

            }
        });

    }

    public Dzg dzg;
    public  List<DzgInspectTask> tasks;

    public String InspectionID="";
    public String InspectionItemID ="";
    public void initData(){
        list = new ArrayList<DzgInspectTask>();

        adapter = new DzgDetailAdapter(list,this);
        listView.setAdapter(adapter);

        dzg = (Dzg) getIntent().getSerializableExtra("detail");
        InspectionID =  getIntent().getStringExtra("InspectionID");
        InspectionItemID =  getIntent().getStringExtra("InspectionItemID");


    }

    @Override
    protected void onResume() {
        super.onResume();

        if(!TextUtils.isEmpty(InspectionID)){
            LogUtils.getInstance().error(" 推送传过来的");
            obtainData(InspectionID,InspectionItemID);

        }else{

            LogUtils.getInstance().error(" 从列表传过来的");
            if( ZjApplication.dzgDetailDB == null){
                obtainData(dzg.getInspectionID() + "", dzg.getInspectItemID() + "");
            }

        }
    }



    public DzgDetail detail;
    public void obtainData(final String inspectionID, final String inspectionItemID){


        dialog = DialogUtil.createProgressDialog(this,"提示","数据获取中..");
        NetManager.getInstance(this).GetToBeRepairedInspectionDetail(inspectionID, inspectionItemID, new OnResponseListener<DzgDetail>() {
            @Override
            public void onComplete(boolean isOK,DzgDetail detail, int errorCode, String errorMsg) {

                try {

                    if(!TextUtils.isEmpty(InspectionID) && detail == null){

                        Toast.makeText(TestDzgDetailActivity.this,"该任务已处理",Toast.LENGTH_SHORT).show();
                        finish();
                        return;

                    }

                    if (detail != null) {
                        DzgDetailDB detailDB = new DzgDetailDB();
                        if(dzg != null){
                            detailDB.setInspectionID(dzg.getInspectionID());
                            detailDB.setInspectionItemID(dzg.getInspectItemID());
                        }else{
                            detailDB.setInspectionID(Integer.parseInt(inspectionID));
                            detailDB.setInspectionItemID(Integer.parseInt(inspectionItemID));
                        }

                        detailDB.setRiskID(detail.getRiskID());
                        ZjApplication.dzgDetailDB = detailDB;
                        String taskName = detail.getInspectTaskName();
                        if(taskName != null && taskName.equals("null")){
                            taskName = "";
                        }

                        rw_tv.setText(taskName);
                        Dic riskDic = dbManager.selector(Dic.class).where("dic_value", "=", detail.RiskType + "").and("dic_type", "=", Constants.RiskType).findFirst();
                        if(riskDic != null){
                            yh_tv.setText(riskDic.getName());
                        }
                        Dic inspectDic = dbManager.selector(Dic.class).where("dic_value", "=", detail.getInspectType() + "").and("dic_type", "=", Constants.InspectType).findFirst();
                        if(inspectDic != null){
                            jcType_tv.setText(inspectDic.getName());
                        }

                        String inspectItemName = detail.getInspectItemName();
                        if(inspectItemName != null && inspectItemName.equals("null")){
                            inspectItemName = "";
                        }
                        jcx_tv.setText(inspectItemName);


                        String orgName = detail.getInspectOrgName();
                        if(orgName != null && orgName.equals("null")){
                            orgName = "";
                        }
                        gs_tv.setText(orgName);
                        String projectName = detail.getInspectProjectName();
                        if(projectName != null && projectName.equals("null")){
                            projectName = "";
                        }
                        xm_tv.setText(projectName);

                        String professionName = detail.getInspectProfessionName();
                        if(professionName != null && professionName.equals("null")){
                            professionName = "";
                        }
                        jczy_tv.setText(professionName);

                        String deadLine = detail.getDeadLine();

                        if(deadLine != null && deadLine.equals("null")){
                            deadLine = "";
                        }

                        deadLine=    deadLine.replace("T", " ");
                        end_date_tv.setText(DateUtil.formatStrimgDate2(deadLine));



                        tasks = detail.getTaskList();
                        int count = 0;
                        if(tasks != null){
                            detailDB.setInpsect_count(tasks.size());
                        }

                        adapter.setDataChange(tasks);
                        setListViewHeightBasedOnChildren(listView);
                    }
                    else{
                        LogUtils.getInstance().error("detail is null");

                    }
                }catch(Exception e){

                    LogUtils.getInstance().error(e.toString());
                }
                dialog.dismiss();
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                dialog.dismiss();

            }
        });
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.left_iv:
                finish();
                break;
            case R.id.right_tv:
                save();

                break;
            case R.id.upload_tv:
                uploadImg();
                break;
            case R.id.check_rl:

                Intent intent = new Intent(TestDzgDetailActivity.this,ZgCheckActivity.class);
                startActivityForResult(intent,JCR);
                break;
        }
    }


    public void save(){
        DbManager dbManager = DBUtil.getInstance(this).getDBManager();
        try {
            if (ZjApplication.dzgDetailDB != null) {
               DzgDetailDB detail =  dbManager.selector(DzgDetailDB.class).where("inspection_id", "=", ZjApplication.dzgDetailDB.getInspectionID()).and("inspectionitem_id", "=", ZjApplication.dzgDetailDB.getInspectionItemID()).findFirst();
               if(detail == null){
                   ZjApplication.dzgDetailDB.setId(UUID.randomUUID().toString());
                   detail = ZjApplication.dzgDetailDB;
               }
                dbManager.saveOrUpdate(detail);
                finish();
            }
        }catch(Exception e){

            LogUtils.getInstance().error(e.toString());
        }
    }
    int count = 0;
    public ProgressDialog dialog;
    public void uploadImg(){


        if(dzg == null){
            Toast.makeText(TestDzgDetailActivity.this, "提交失败", Toast.LENGTH_SHORT).show();
            return;
        }
        final DbManager dbManager = DBUtil.getInstance(this).getDBManager();

        count = 0;
        try{
            if (ZjApplication.dzgDetailDB != null) {
                DzgDetailDB detail =  dbManager.selector(DzgDetailDB.class).where("inspection_id", "=", ZjApplication.dzgDetailDB.getInspectionID()).and("inspectionitem_id", "=", ZjApplication.dzgDetailDB.getInspectionItemID()).findFirst();
                if(detail == null){
                    ZjApplication.dzgDetailDB.setId(UUID.randomUUID().toString());
                    detail = ZjApplication.dzgDetailDB;
                }
                dbManager.saveOrUpdate(detail);
            }
           final List<DzgInspectItemDB> items =  dbManager.selector(DzgInspectItemDB.class).where("inspectid", "=", dzg.getInspectionID()).findAll();

            if(items != null && tasks.size() == items.size()){

                for(final DzgInspectItemDB item:items){
                   String img =  item.getImgs();
                    dialog = DialogUtil.createProgressDialog(this,"提示","上传图片中..");
                    NetManager.getInstance(this).newUploadImg(img, new OnResponseListener<List<UploadFile>>() {
                       @Override
                       public void onComplete(boolean isOK, List<UploadFile> result, int errorCode, String errorMsg) {

                           if(isOK){
                               count ++;
                               dialog.setMessage("上传数据中...");
                               StringBuffer sb = new StringBuffer();
                               for(UploadFile file:result){
                                   sb.append(file.getResourceId());
                                   sb.append(",");
                               }
                               item.setUploadImgs(sb.toString());
                               try {
                                   dbManager.saveOrUpdate(item);
                               } catch (DbException e) {
                                   e.printStackTrace();
                               }

                               if(count == items.size()){
                                   doSumbitData();
                               }

                           }else{
                               dialog.dismiss();
                               Toast.makeText(TestDzgDetailActivity.this, " 上传失败", Toast.LENGTH_SHORT).show();

                           }
                       }

                       @Override
                       public void onInternError(int errorCode, String errorMessage) {
                           dialog.dismiss();

                           Toast.makeText(TestDzgDetailActivity.this, " 上传失败", Toast.LENGTH_SHORT).show();
                       }
                   });
                }
            }else{

                Toast.makeText(TestDzgDetailActivity.this, "请填写相应的整改项内容", Toast.LENGTH_SHORT).show();
            }
        }catch (Exception e){

        }


    }

    public void doSumbitData(){

        NetManager.getInstance(this).AddRepairRecord(dzg, new OnResponseListener<Dzg>() {
            @Override
            public void onComplete(boolean isOK, Dzg result, int errorCode, String errorMsg) {


                if(isOK){
                    dialog.dismiss();

                    DbManager dbManager = DBUtil.getInstance(TestDzgDetailActivity.this).getDBManager();
                    try {
                        DzgDetailDB detail =  dbManager.selector(DzgDetailDB.class).where("inspection_id", "=", dzg.getInspectionID()).where("inspectionitem_id", "=", dzg.getInspectItemID()).findFirst();
                        if(detail != null){
                            dbManager.delete(detail);

                        }
                        List<DzgInspectItemDB> items =  dbManager.selector(DzgInspectItemDB.class).where("inspectionitem_id", "=", dzg.getInspectItemID()).findAll();
                        if(items != null){
                            for(DzgInspectItemDB item:items){
                                dbManager.delete(item);
                            }
                        }
                    } catch (DbException e) {
                        e.printStackTrace();
                    }

                    ZjApplication.dzgInspectItemDB = null;
                    ZjApplication.dzgDetailDB = null;
                    Toast.makeText(TestDzgDetailActivity.this, " 提交成功", Toast.LENGTH_SHORT).show();
                    finish();

                }else{
                    dialog.dismiss();
                    Toast.makeText(TestDzgDetailActivity.this, " 提交失败", Toast.LENGTH_SHORT).show();

                }
            }

            @Override
            public void onInternError(int errorCode, String errorMessage) {
                dialog.dismiss();

                Toast.makeText(TestDzgDetailActivity.this, " 提交失败", Toast.LENGTH_SHORT).show();

            }
        });


    }

    public void setListViewHeightBasedOnChildren(ListView listView) {

        ListAdapter listAdapter = listView.getAdapter();

        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;

        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));


        listView.setLayoutParams(params);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode == RESULT_OK){

            if(requestCode == JCR){

               User user = (User) data.getSerializableExtra("user");
               if(user != null){
                   check_value_tv.setText(user.getUserName());
               }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
